package com.ruibo.modules.security.service;

import com.ruibo.exception.BadRequestException;
import com.ruibo.modules.security.config.bean.LoginProperties;
import com.ruibo.modules.security.security.vo.JwtUser;
import com.ruibo.modules.system.service.SysRoleService;
import com.ruibo.modules.system.service.SysUserService;
import com.ruibo.modules.system.service.dto.DeptSmallDto;
import com.ruibo.modules.system.service.dto.JobSmallDto;
import com.ruibo.modules.system.service.dto.SysUserDto;
import com.ruibo.utils.SpringContextHolder;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

/**
 * @ClassName : UserDetailsServiceImpl  //类名
 * @Description : //描述
 * @Author : sunfeng
 * @Date: 2020-04-19 13:02  //时间
 */
@Service("userDetailsService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class UserDetailsServiceImpl  implements UserDetailsService {
    private final SysUserService userService;
    private final SysRoleService roleService;
    private final LoginProperties loginProperties;
    public UserDetailsServiceImpl(SysUserService userService, SysRoleService roleService, LoginProperties loginProperties) {
        this.userService = userService;
        this.roleService = roleService;
        this.loginProperties = loginProperties;
    }

    @Override
    public UserDetails loadUserByUsername(String username){
        SysUserDto user = userService.findByName(username);
        if (user == null) {
            throw new BadRequestException(HttpStatus.INTERNAL_SERVER_ERROR,"账号不存在");
        } else {
            if (!user.getStatus().equals("0")) {
                throw new BadRequestException("账号未激活");
            }
            return createJwtUser(user);
        }
    }

    private UserDetails createJwtUser(SysUserDto user) {
        JwtUser jwtUser = new JwtUser(
                user.getId(),
                user.getUserName(),
                user.getNickName(),
                user.getSex(),
                user.getPassword(),
                user.getAvatar(),
                user.getEmail(),
                user.getPhoneNumber(),
                Optional.ofNullable(user.getDept()).map(DeptSmallDto::getDeptName).orElse(null),
                Optional.ofNullable(user.getJob()).map(JobSmallDto::getName).orElse(null),
                roleService.mapToGrantedAuthorities(user),
                user.getStatus().equals("0"),
                user.getCreatedDate(),
                user.getLastModifiedDate()
        );
        return jwtUser;
    }
}
